var path = require('path')
var webpack = require('webpack')
var cheerio = require('cheerio')
var fs = require('fs')
const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath:  process.env.NODE_ENV === 'production' ? '/Application/Home/View/Index/dist/' : '/dist/',
    filename: process.env.NODE_ENV === 'production' ? 'build.[hash:5].js' : 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
        // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: 'images/[name].[ext]?[hash]'
        }
      },
      {
        test: /\.less$/,
        loader: 'style-loader!css-loader!less-loader'
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    port: 8080
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    }),
    new CleanWebpackPlugin(
      ['dist/build.*.js', 'dist/build.*.js.map', 'dist/*.build.*.js', 'dist/*.build.*.js.map'], // 匹配删除的文件
      {
        root: __dirname, // 根目录
        verbose: true, // 开启在控制台输出信息
        dry: false // 启用删除文件
      }
    )
  ]).concat([
    function () {
      this.plugin('done', stats => {
        fs.readFile('./index.html', (err, data) => {
          var time = new Date().getTime()
          const $ = cheerio.load(data.toString())
          var hash = stats.hash.substring(0, 5)
          $('script[name=dist]').attr('src', '__ROOT__/Application/Home/View/Index/dist/build.' + hash + '.js')
          fs.writeFile('./index.html', $.html(), err => {
            console.log(hash)
          })
        })
      })
    }
  ])
}
